home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 5978 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.3 KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: How do I round and truncate floats to integers?
  5. Date: Thu, 22 Feb 96 01:02:13 GMT
  6. Organization: none
  7. Message-ID: <824950933snz@genesis.demon.co.uk>
  8. References: <4g009b$c2n@news.tuwien.ac.at> <harmon.824447677@pegasus.montclair.edu> <Dn4oM5.1JK@uns.bris.ac.uk>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <Dn4oM5.1JK@uns.bris.ac.uk>
  15.            nathan@pact.srf.ac.uk "Nathan Sidwell" writes:
  16.  
  17. >Now it just so happens that when the result of casting a signed int to an
  18. >unsigned int is not implementation defined (ie the value to
  19. >be converted is representable in both types), there is no change
  20. >to the bit pattern, for a common representation of binary integers (twos
  21. >complement).
  22.  
  23. If the value is representable in both types it is a non-negative value. From
  24. 6.1.2.5
  25.  
  26. "The range of nonnegative values of a signed integer is a subrange of the
  27. corresponding unsigned integer type, and the representation of the same
  28. value in each case is the same"
  29.  
  30. So what you say above is true for any legal representation, not just 2's
  31. complement.
  32.  
  33. The only thing that is implementation defined about converting a signed
  34. int to an unsigned int is the value of UINT_MAX. 
  35.  
  36. >Many compilers extend the conversion in an implementation
  37. >defined manner, so that there is never a change in the bit pattern.
  38.  
  39. This is the consequence of using 2's complement representation.
  40.  
  41. >This may be where your confusion is coming from.
  42.  
  43. Simply remember that the effects of a cast are defined on an object's type
  44. and value, *not* its representation. For example the result of converting
  45. (either implicitly or by using a cast) a floating point value to an
  46. integer value is to truncate the value to the nearest integer that is smaller
  47. in magnitude (i.e. discard the fractional part). If the resulting value
  48. can't be represented in the target type the behaviour is undefined. This
  49. can clearly result in a complete change in the bit pattern involved, even
  50. in the number of bits in the value.
  51.  
  52. -- 
  53. -----------------------------------------
  54. Lawrence Kirby | fred@genesis.demon.co.uk
  55. Wilts, England | 70734.126@compuserve.com
  56. -----------------------------------------
  57.